package cn.lopr.im.android.mvp.view.activities;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.drawerlayout.widget.DrawerLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.nineoldandroids.view.ViewHelper;

import java.util.HashMap;
import java.util.Map;

import cn.lopr.im.android.R;
import cn.lopr.im.android.bean.User;
import cn.lopr.im.android.common.app.Activity;
import cn.lopr.im.android.databinding.ActivityMainBinding;
import cn.lopr.im.android.db.helper.DaoUtilsStore;
import cn.lopr.im.android.mvp.view.fragments.CommunityFragment;
import cn.lopr.im.android.mvp.view.fragments.ContactFragment;
import cn.lopr.im.android.mvp.view.fragments.HomeFragment;
import cn.lopr.im.android.mvp.view.helper.NavHelper;
import cn.lopr.im.android.service.ForegroundService;
import cn.lopr.im.android.service.MessageService;

public class MainActivity extends Activity implements NavHelper.OnTabChangedListener<Integer>,
        BottomNavigationView.OnNavigationItemSelectedListener {

    private ActivityMainBinding binding;

    public static User user;

    private NavHelper<Integer> navHelper;
    private final String TAG = "MainActivity";

    private Map<Integer, String> nameMapping = new HashMap<Integer, String>() {{
        put(R.id.action_home, "消息");
        put(R.id.action_contact, "通讯录");
        put(R.id.action_community, "社区");
    }};

    @Override
    protected View getContentLayoutId() {
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    protected void initWidget() {
        super.initWidget();

        //蒙层颜色
        binding.drawerLayout.setScrimColor(getResources().getColor(R.color.colorGray));
        binding.drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerStateChanged(int newState) {
            }

            @Override
            public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
                View mContent = binding.drawerLayout.getChildAt(0);
                View mMenu = drawerView;
                ViewHelper.setTranslationX(mContent, mMenu.getMeasuredWidth() * slideOffset);
            }

            @Override
            public void onDrawerOpened(@NonNull View drawerView) {

            }

            @Override
            public void onDrawerClosed(@NonNull View drawerView) {
            }
        });

        navHelper = new NavHelper<>(this, R.id.lay_container, getSupportFragmentManager(), this);
        navHelper.add(R.id.action_home, new NavHelper.Tab<>(HomeFragment.class, R.string.title_home));
        navHelper.add(R.id.action_contact, new NavHelper.Tab<>(ContactFragment.class, R.string.title_contact));
        navHelper.add(R.id.action_community, new NavHelper.Tab<>(CommunityFragment.class, R.string.title_community));

        binding.navigation.setOnNavigationItemSelectedListener(this);

        binding.ivPortrait.setOnClickListener(e -> binding.drawerLayout.open());

        binding.toolbar.setOnMenuItemClickListener(e -> {
            if (e.getItemId() == R.id.add) {
                Intent intent = new Intent(MainActivity.this, AddFriendActivity.class);
                intent.putExtra("user", user);
                intent.putExtra("action", "search");
                startActivity(intent);
            } else if (e.getItemId() == R.id.add_article) {
                Intent intent = new Intent(MainActivity.this, ArticlePublishActivity.class);
                intent.putExtra("user", user);
                intent.putExtra("action", "add");
                startActivity(intent);
            }
            return true;
        });

        binding.ivHeadLeft.setOnClickListener(e -> {
            Intent info = new Intent(MainActivity.this, InfoActivity.class);
            info.putExtra("user", user);
            info.putExtra("isFriend", true);
            startActivity(info);
        });
        binding.llInfoLeft.setOnClickListener(e -> startActivity(new Intent(this, AboutActivity.class)));
    }

    @Override
    protected void initData() {
        super.initData();
        createNotificationChannel();

        DaoUtilsStore.init(getApplication());

        Menu menu = binding.navigation.getMenu();

        // 触发首次选中Home
        menu.performIdentifierAction(R.id.action_home, 0);

        user = (User) getIntent().getExtras().getSerializable("user");
        getIntent().getSerializableExtra("user");

        // 开启服务
        Intent intent = new Intent(this, MessageService.class);
        intent.putExtra("phone", user.getPhone());
        startService(intent);

        startService(new Intent(this, ForegroundService.class));

        binding.tvNameLeft.setText(user.getNickname());

        Glide.with(getApplicationContext()).load(user.getPortrait()).placeholder(R.drawable.default_head_portrait)
                .dontAnimate()
                .into(new SimpleTarget<GlideDrawable>() {
                    @Override
                    public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                        binding.ivPortrait.setImageDrawable(resource);
                        binding.ivHeadLeft.setImageDrawable(resource);
                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        super.onLoadFailed(e, errorDrawable);
                        binding.ivPortrait.setImageDrawable(errorDrawable);
                    }
                });
    }


    @Override
    public void onTabChanged(NavHelper.Tab<Integer> newTab, NavHelper.Tab<Integer> oldTab) {

    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        this.binding.txtTitle.setText(nameMapping.get(item.getItemId()));
        return navHelper.performClickMenu(item.getItemId());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = getString(R.string.app_name);
            String description = getString(R.string.channel_description);
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel("10086", name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

}